//
//  EncryptWithKey.m
//  HiQ
//
//  Created by maxwellpang on 12-8-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "EncryptorWithKey.h"

@implementation EncryptorWithKey

+(NSData*) encryptWithKey:(NSData *)data forKey:(NSString *)key
{
    NSData *result = nil;
    
    //设置key
    char cKey[ENCRYPT_KEY_SIZE + 1];
    bzero(cKey, sizeof(cKey));    
    [key getCString:cKey maxLength:sizeof(cKey) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];

    //输出buffer
    size_t bufferSize = dataLength + ENCRYPT_BLOCK_SIZE;
	void *buffer = malloc(bufferSize);
	
    //加密过程
	size_t numBytesEncrypted = 0;
	CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, 
                                          ENCRYPT_ALGORITHM, 
                                          kCCOptionPKCS7Padding,
										  cKey, 
                                          ENCRYPT_KEY_SIZE,
										  NULL, 
										  [data bytes],
                                          dataLength, 
										  buffer,
                                          bufferSize, 
										  &numBytesEncrypted);
    
    

    //如果成功返回数据
    //不成功释放buffer打出LOG，并返回nil
    if (cryptStatus == kCCSuccess) {
		result = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
	} else {
        free(buffer);
        NSLog(@"[ERROR] failed to encrypt|CCCryptoStatus: %d", cryptStatus);
    }
	
	return result;
}

+(NSData*) decryptWIthKey:(NSData *)data forKey:(NSString *)key
{
    NSData *result = nil;
    
    //设置key
    char cKey[ENCRYPT_KEY_SIZE + 1];
    bzero(cKey, sizeof(cKey));
    [key getCString:cKey maxLength:sizeof(cKey) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    
    //输出buffer
    size_t bufferSize = dataLength + ENCRYPT_BLOCK_SIZE;
	void *buffer = malloc(bufferSize);
	
    //解密过程
	size_t numBytesEncrypted = 0;
	CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, 
                                          ENCRYPT_ALGORITHM, 
                                          kCCOptionPKCS7Padding,
										  cKey, 
                                          ENCRYPT_KEY_SIZE,
										  NULL, 
										  [data bytes],
                                          dataLength, 
										  buffer,
                                          bufferSize, 
										  &numBytesEncrypted);
    
    
    
    //如果成功返回数据
    //不成功释放buffer打出LOG，并返回nil
    if (cryptStatus == kCCSuccess) {
		result = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
	} else {
        free(buffer);
        NSLog(@"[ERROR] failed to encrypt|CCCryptoStatus: %d", cryptStatus);
    }
	
	return result;
}


@end
